<template>
  <div class="content">
    <div class="lucky-container">
      <img class="bg" src="/static/bg.png" />
      <div class="title">郑千白切粉丝福利</div>
      <div class="slot-container">
        <SlotMachine
          ref="myLucky"
          width="560rpx"
          height="320rpx"
          :blocks="blocks"
          :prizes="prizes"
          :slots="slots"
          :defaultConfig="defaultConfig"
          @end="end"
        />
      </div>
      <div class="logo">郑千白切</div>
      <div class="lucky-btn" @click="startLucky">
        {{
          existGroup
            ? countFlag
              ? btnLock
                ? "幸运转动中"
                : "开始抽奖"
              : "抽奖次数已用完"
            : "加入粉丝群抽奖"
        }}
      </div>
    </div>
    <div class="lucky-list" v-if="prizeList.length > 0">
      <p class="title">奖品列表</p>
      <div class="lucky-item" v-for="item in prizeList" :key="item.prizeId">
        <img class="prize-image" src="/static/huawei.png" />
        {{ item.prizeName }}
      </div>
    </div>
    <div class="activity-desc">
      <p class="title">活动说明</p>
      <div class="content-list">
        <p class="content-item">
          微信下拉:搜索小程序 并打开--点右下角礼物盒标志
          -“待兑换”里会显示中奖信息，打开凭中奖码到店兑奖核销即可。
        </p>
        <p class="content-item">中奖之日起7日内到店核销即可兑换使用。</p>
      </div>
      <p class="time">开始时间：{{ startTime }}</p>
      <p class="time">结束时间：{{ endTime }}</p>
    </div>
    <button open-type="share">分享抽奖活动</button>

    <div class="gift" @click="toGift">
      <u-icon name="gift-fill" color="#fd0100" size="32"></u-icon>
    </div>
  </div>
</template>

<script>
import SlotMachine from "@lucky-canvas/uni/slot-machine"; // 老虎机
// 完整加载
export default {
  components: {
    SlotMachine,
  },
  data() {
    return {
      existGroup: false,
      countFlag: false,
      level: null,
      prizeName: null,
      blocks: [
        {
          background: "#d22f10",
        },
      ],
      slots: [{ speed: 30 }, { speed: 15 }, { speed: 20 }],
      prizes: [
        {
          fonts: [
            {
              text: "小米", //文字
              top: "70%", //文字距顶部距离
              fontColor: "#000", //文字颜色
              fontSize: "24rpx", //文字大小
              fontStyle: "微软雅黑", //字体
              fontWeight: "500", //加粗
              lineHeight: "32rpx", //行高
              wordWrap: true, //换行
              lineClamp: 2, //2行，剩下的...
            },
          ],
          background: "#fefaee",
          padding: "10rpx",
          imgs: [
            {
              top: "10%",
              width: "50%",
              height: "50%",
              src: "/static/xiaomi.png",
            },
          ],
        },
        {
          fonts: [
            {
              text: "华为", //文字
              top: "70%", //文字距顶部距离
              fontColor: "#000", //文字颜色
              fontSize: "24rpx", //文字大小
              fontStyle: "微软雅黑", //字体
              fontWeight: "500", //加粗
              lineHeight: "32rpx", //行高
              wordWrap: true, //换行
              lineClamp: 2, //2行，剩下的...
            },
          ],
          background: "#fefaee",
          borderRadius: "10rpx",
          padding: "10rpx",
          imgs: [
            {
              top: "10%",
              width: "50%",
              height: "50%",
              src: "/static/huawei.png",
            },
          ],
        },
        {
          fonts: [
            {
              text: "一加", //文字
              top: "70%", //文字距顶部距离
              fontColor: "#000", //文字颜色
              fontSize: "24rpx", //文字大小
              fontStyle: "微软雅黑", //字体
              fontWeight: "500", //加粗
              lineHeight: "32rpx", //行高
              wordWrap: true, //换行
              lineClamp: 2, //2行，剩下的...
            },
          ],
          background: "#fefaee",
          borderRadius: "10rpx",
          padding: "10rpx",
          imgs: [
            {
              top: "10%",
              width: "50%",
              height: "50%",
              src: "/static/oneplus.png",
            },
          ],
        },
      ],
      defaultConfig: {
        rowSpacing: "20rpx",
        colSpacing: "20rpx",
      },
      activeIndex: null,
      btnLock: false,
      prizeList: [],
      startTime: null,
      endTime: null,
    };
  },
  onShareAppMessage() {
    return {
      title: "幸运抽奖",
      path: "/pages/index/index",
    };
  },
  onLoad() {
    if (!uni.getStorageSync("token")) {
      this.login();
    } else {
      this.checkGroup();
    }
  },
  onShow() {
    if (uni.getStorageSync("token")) {
      this.getLottery();
      this.getPrizeList();
    }
  },
  methods: {
    login() {
      let that = this;
      uni.login({
        provider: "weixin",
        success: function (loginRes) {
          let params = {};
          params.code = loginRes.code;
          that.$Api.main.home.login(params).then(async (res) => {
            const openId = res.data.openid;
            await that.$store.dispatch("token", openId);
            that.checkGroup();
            that.getLottery();
            that.getPrizeList();
          });
        },
      });
    },
    checkGroup() {
      let that = this;
      wx.getGroupEnterInfo({
        success: (res) => {
          let params = {};
          params.iv = res.iv;
          params.encryptedData = res.encryptedData;
          that.$Api.main.home.encryptData(params).then(async (enRes) => {
            that.countFlag = enRes.countFlag;
            that.existGroup = enRes.existGroup;
          });
        },
      });
    },
    // 执行组合排列的函数
    doExchange(arr) {
      let len = arr.length;
      // 当数组大于等于2个的时候
      if (len >= 2) {
        // 第一个数组的长度
        let len1 = arr[0].length;
        // 第二个数组的长度
        let len2 = arr[1].length;
        // 2个数组产生的组合数
        let lenBoth = len1 * len2;
        //  申明一个新数组,做数据暂存
        let items = new Array(lenBoth);
        // 申明新数组的索引
        let index = 0;
        // 2层嵌套循环,将组合放到新数组中
        for (let i = 0; i < len1; i++) {
          for (let j = 0; j < len2; j++) {
            items[index] = arr[0][i] + "," + arr[1][j];
            index++;
          }
        }
        // 将新组合的数组并到原数组中
        let newArr = new Array(len - 1);
        for (let i = 2; i < arr.length; i++) {
          newArr[i - 1] = arr[i];
        }
        newArr[0] = items;
        // 执行回调
        return this.doExchange(newArr);
      } else {
        return arr[0];
      }
    },
    startLucky() {
      if (!this.existGroup) {
        uni.showModal({
          title: "温馨提示",
          content: "参与抽奖请联系店员加入粉丝群后获得抽奖机会!",
          showCancel: false,
        });
        return false;
      }
      if (!this.countFlag) {
        uni.showModal({
          title: "温馨提示",
          content: "抽奖次数已用完!",
          showCancel: false,
        });
        return false;
      }
      if (this.existGroup && this.countFlag) {
        this.start();
      }
    },
    start() {
      if (!this.btnLock) {
        this.btnLock = true;
        this.$Api.main.home
          .lottery()
          .then((res) => {
            this.level = res.data.level;
            this.prizeName = res.data.prizeName;
            // 开始转动
            this.$refs.myLucky.play();
            if (this.level > 0) {
              // 幸运数组
              const luckyList = [
                [0, 0, 0],
                [1, 1, 1],
                [2, 2, 2],
              ];
              this.$refs.myLucky.stop(luckyList[this.level - 1]);
            } else {
              // 3乘3排列全组合
              let array = [
                [0, 1, 2],
                [0, 1, 2],
                [0, 1, 2],
              ];
              let randomList = this.doExchange(array);
              randomList = randomList
                .filter((item) => {
                  return (
                    item !== "0,0,0" && item !== "1,1,1" && item !== "2,2,2"
                  );
                })
                .map((item) => {
                  return item.split(",").map((e) => Number(e));
                });
              // 随机取一组数据
              const randomIndex = (Math.random() * randomList.length) >> 0;
              // 调用 stop 方法停止游戏
              this.$refs.myLucky.stop(randomList[randomIndex]);
            }
          })
          .catch(() => {
            this.btnLock = false;
          });
      }
    },
    end() {
      this.btnLock = false;
      if (this.level === 0) {
        uni.showModal({
          title: "中奖提示",
          content: this.prizeName,
          showCancel: false,
        });
      } else {
        uni.showModal({
          title: "抽奖结果",
          content: this.prizeName,
          showCancel: false,
        });
        this.getPrizeList();
      }
      this.getLotteryCount();
    },
    getPrizeList() {
      this.$Api.main.lottery.getPrizeList().then((res) => {
        this.prizeList = res.data;
      });
    },
    getLotteryCount() {
      this.$Api.main.home.getLotteryCount().then((res) => {
        this.countFlag = res.countFlag;
      });
    },
    getLottery() {
      this.$Api.main.lottery.getLottery().then((res) => {
        this.startTime = res.data[0].starttime;
        this.endTime = res.data[0].endtime;
      });
    },
    toGift() {
      uni.navigateTo({
        url: "/pages/gift/gift",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  padding-bottom: 60rpx;
  .lucky-container {
    width: 710rpx;
    height: 838rpx;
    margin: 40rpx auto;
    position: relative;
    .bg {
      width: 100%;
      height: 100%;
    }
    .title {
      color: #d22f10;
      position: absolute;
      top: 10rpx;
      left: 0;
      text-align: center;
      font-weight: 600;
      width: 100%;
      font-size: 28rpx;
    }
    .logo {
      color: #000;
      position: absolute;
      left: 34rpx;
      bottom: 184rpx;
      font-size: 30rpx;
      font-weight: 600;
    }
    .slot-container {
      position: absolute;
      left: 76rpx;
      top: 130rpx;
    }
    .lucky-btn {
      width: 300rpx;
      line-height: 80rpx;
      background: #f05237;
      /*border: 8rpx solid #fffdb3;*/
      text-align: center;
      border-radius: 50rpx;
      color: #fff;
      margin-top: 40rpx;
      font-weight: 600;
      position: absolute;
      left: 50%;
      margin-left: -150rpx;
      bottom: 110rpx;
    }
  }
  .lucky-list {
    width: 680rpx;
    margin: 40rpx auto;
    background: #fff;
    padding: 30rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
    .title {
      color: #eb5f14;
      font-size: 34rpx;
      font-weight: 600;
      text-align: center;
      padding-bottom: 24rpx;
      border-bottom: 1rpx solid #e9e9e9;
    }
    .lucky-item {
      border-bottom: 1rpx solid #e9e9e9;
      padding: 24rpx 40rpx;
      font-size: 26rpx;
      display: flex;
      align-items: center;
      .prize-image {
        width: 50rpx;
        height: 50rpx;
        margin-right: 20rpx;
      }
    }
  }
  .activity-desc {
    width: 680rpx;
    margin: 40rpx auto;
    background: #fff;
    padding: 30rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
    .title {
      color: #eb5f14;
      font-size: 34rpx;
      font-weight: 600;
      text-align: center;
      padding-bottom: 24rpx;
    }
    .content-list {
      margin-bottom: 20rpx;
      .content-item {
        font-size: 32rpx;
      }
    }
    .time {
      color: #808080;
      font-size: 26rpx;
    }
  }
  .gift {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #ffe562;
    position: fixed;
    bottom: 40rpx;
    right: 20rpx;
    padding: 14rpx;
    border-radius: 50%;
    box-shadow: rgba(0, 0, 0, 0.2) 0 2px 8px;
  }
  button::after {
    border: none;
  }
  button {
    width: 680rpx;
    margin: 40rpx auto;
    background: #fff;
    box-sizing: border-box;
    border-radius: 10rpx;
    text-align: center;
    font-size: 36rpx;
  }
}
</style>
